package com.example.gymmanagement.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.Update;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.gymmanagement.Utils.Result;
import com.example.gymmanagement.Utils.StatusCode;
import com.example.gymmanagement.domain.Bill;
import com.example.gymmanagement.domain.Equip;
import com.example.gymmanagement.domain.Rent;
import com.example.gymmanagement.domain.User;
import com.example.gymmanagement.mapper.BillMapper;
import com.example.gymmanagement.mapper.RentMapper;
import com.example.gymmanagement.service.BillService;
import com.example.gymmanagement.service.EquipService;
import com.example.gymmanagement.mapper.EquipMapper;
import com.example.gymmanagement.service.RentService;
import com.example.gymmanagement.service.UserService;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.awt.print.PrinterAbortException;
import java.sql.Wrapper;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
* @author 13726256113
* @description 针对表【equip】的数据库操作Service实现
* @createDate 2023-06-06 15:22:32
*/
@Service
public class EquipServiceImpl extends ServiceImpl<EquipMapper, Equip>
    implements EquipService{
    @Autowired
    private EquipMapper equipMapper;
    @Autowired
    private BillService billService;
    @Autowired
    private UserService userService;
    @Autowired
    private RentService rentService;
    @Override
    public Result insert(Equip equip, Integer count, String token) {
        //默认增1
        if (count==null||count==0){
            count=1;
        }

        QueryWrapper<Equip> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("equip_id").last("LIMIT 1");
        Equip equip1 = equipMapper.selectOne(wrapper);
        long id = equip1.getEquipId();
        for(int i=1;i<=count;i++){
            equip.setEquipId(++id);
            boolean flag1 = this.equipMapper.insert(equip)>0;
            if(!flag1){
                return new Result(StatusCode.SAVE_ERR,flag1,"新增器材失败");
            }
        }
        //通过token获取登录用户id
        User user = (User)this.userService.selectCurrentUser(token).getData();
        //新增购置器材账单
        Bill bill = new Bill();
        bill.setBillTime(LocalDateTime.now());
        bill.setBillUser(user.getUserNum());
        bill.setBillPrice(Double.valueOf(equip.getEquipPrice())*count);
        bill.setBillType("器材购置");
        bill.setBillDetail("购置"+count+"个"+equip.getEquipName());
        boolean flag2 = billService.insert(bill);
        if (!flag2){
            return new Result(StatusCode.SAVE_ERR,flag2,"新增购置账单失败");
        }
        return new Result(StatusCode.SAVE_OK,true,"新增器材成功");
    }

    @Override
    public Result delete(Integer id) {
        Equip equip = equipMapper.selectById(id);
        if(equip==null){
            return new Result(StatusCode.GET_ERR,false,"器材不存在");
        }
        boolean flag = this.equipMapper.deleteById(id)>0;
        String msg = flag?"删除成功":"删除失败";
        return new Result(StatusCode.DELETE_OK,flag,msg);
    }

    @Override
    public boolean updateEquip(Equip equip) {
        return this.equipMapper.updateById(equip)>0;
    }

    @Override
    public Equip selectById(Integer id) {
        return (Equip) this.equipMapper.selectById(id);
    }

    @Override
    public Result selectUnused(String equipName, Integer index, Integer size) {
        //默认第一页开始，每页5条
        if(index==null ||index==0){
            index=1;
        }
        if (size==null ||size ==0){
            size=5;
        }
        Page<Equip> pageInfo = new Page(index,size);
        LambdaQueryWrapper<Equip> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //按器材名查找闲置的器材
        lambdaQueryWrapper.like(null!=equipName,Equip::getEquipName,equipName).eq(Equip::getEquipStatus,"闲置");
        Page<Equip> equipList = (Page) this.equipMapper.selectPage(pageInfo,lambdaQueryWrapper);
        Integer code = equipList!=null? StatusCode.GET_OK:StatusCode.GET_ERR;
        String msg = equipList!=null?"查询成功":"查询失败";
        return new Result(code,equipList,msg);

    }

    @Override
    public Result rent(long equipId,long match, String token) {
        Equip equip = equipMapper.selectById(equipId);
        //不是闲置不可租借
        if (equip.getEquipStatus()!="闲置中"){
            return new Result(StatusCode.UPDATE_ERR,false,"该器材不可被租借");
        }
        if(equip==null){
            return new Result(StatusCode.GET_ERR,false,"器材不存在");
        }
        //通过token获取登录用户id
        User user = (User)this.userService.selectCurrentUser(token).getData();
        long uid = user.getUserNum();
        //找到租借的器材，更新器材状态,更新时间
        UpdateWrapper<Equip> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("equip_id",equipId).set("equip_status","租借中").set("equip_updatetime", LocalDateTime.now());
        boolean flag = equipMapper.update(null,updateWrapper)>0;
        if (!flag){
            return new Result(StatusCode.UPDATE_ERR,flag,"器材更新失败");
        }
        //租借表增加租借记录
        Rent rent = new Rent();
        if (match!=0){
            rent.setRentMatch(match);
        }
        rent.setRentEquip(equipId);
        rent.setRentUser(uid);
        rent.setRentType("器材租借");
        rent.setRentStatus("进行中");
        rent.setRentPrice(Double.valueOf(equip.getEquipPrice()));
        rent.setRentDtail("租借"+equip.getEquipName());
        rent.setRentStart(LocalDateTime.now());
        boolean flag1 = this.rentService.insert(rent);
        if (!flag1){
            return new Result(StatusCode.SAVE_ERR,flag,"新建租借记录失败");
        }
        return new Result(StatusCode.SAVE_OK,"租借成功");
    }

    @Override
    public Result returnEquip(long equipId, Integer broken,String token) {
        //通过token获取登录用户id
        User user = (User)this.userService.selectCurrentUser(token).getData();
        long uid = user.getUserNum();
        //取出器材表对象
        Equip equip = equipMapper.selectById(equipId);
        //查询租借表，判断器材是否已经归还
        QueryWrapper<Rent> queryWrapper1= new QueryWrapper<>();
        queryWrapper1.eq("rent_user",uid).eq("rent_equip",equipId).eq("rent_status","进行中");
        Rent rent1 = rentService.getOne(queryWrapper1);
        if (rent1==null){
            return new Result(StatusCode.UPDATE_ERR,"您已归还器材");
        }
        //取出租借表对应对象
        QueryWrapper<Rent> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("rent_user",uid).eq("rent_equip",equipId).eq("rent_status","进行中");
        Rent rent = rentService.getOne(queryWrapper);

        //找到租借的器材，更新器材状态,更新时间
        UpdateWrapper<Equip> updateWrapper1 = new UpdateWrapper<>();
        updateWrapper1.eq("equip_id",equipId).set("equip_status","闲置").set("equip_updatetime",LocalDateTime.now());
        boolean flag1 = equipMapper.update(null, updateWrapper1)>0;
        if (!flag1){
            return new Result(StatusCode.UPDATE_ERR,"更新器材失败");
        }
        //更新租借表
        UpdateWrapper<Rent> updateWrapper2 = new UpdateWrapper<>();
        updateWrapper2.eq("rent_equip",equipId).set("rent_end",LocalDateTime.now()).set("rent_status","已完成");
        boolean flag2 = rentService.update(null,updateWrapper2);
        if (!flag2){
            return new Result(StatusCode.UPDATE_ERR,"更新租借记录失败");
        }
        //生成账单
        Bill bill = new Bill();
        //计算租借时长
        Duration duration = Duration.between(rent.getRentStart(),LocalDateTime.now());
        long seconds = duration.getSeconds();
        //按小时计算费用
        double price = ((double) seconds/3600)*rent.getRentPrice();
        bill.setBillUser(uid);
        bill.setBillDetail("租借"+equip.getEquipName());
        bill.setBillType("器材租借");
        bill.setBillPrice(price);
        bill.setBillTime(LocalDateTime.now());
        bill.setBillDetail("租借"+equip.getEquipName());
        boolean flag3 =billService.insert(bill);
        if(!flag3){
            return new Result(StatusCode.SAVE_ERR,"添加账单失败");
        }
        //器材有损毁，生成赔偿账单
        if(broken==1){
            //修改器材状态
            UpdateWrapper<Equip> updateWrapper3 = new UpdateWrapper<>();
            updateWrapper3.eq("equip_id",equipId).set("equip_status","损毁").set("equip_updatetime",LocalDateTime.now());
            equipMapper.update(null,updateWrapper3);
            //生成账单
            Bill bill1 = new Bill();
            bill1.setBillUser(uid);
            bill1.setBillPrice(Double.valueOf(equip.getEquipDamages()));
            bill1.setBillType("器材赔偿");
            bill1.setBillTime(LocalDateTime.now());
            bill1.setBillDetail("赔偿"+equip.getEquipName());
            boolean flag4 = billService.insert(bill1);
            if (!flag4){
                return new Result(StatusCode.SAVE_ERR,"添加账单失败");
            }
        }
        return new Result(StatusCode.UPDATE_OK,"归还成功");
    }

    @Override
    public Result repair(long equipId, double repairPrice,String token) {
        //通过token获取登录用户id
        User user = (User)this.userService.selectCurrentUser(token).getData();
        long uid = user.getUserNum();
        //取出器材表和租借表对应对象
        Equip equip = equipMapper.selectById(equipId);
        //找到租借的器材，更新器材状态,更新时间
        UpdateWrapper<Equip> updateWrapper1 = new UpdateWrapper<>();
        updateWrapper1.eq("equip_id",equipId).set("equip_status","报修中").set("equip_updatetime",LocalDateTime.now());
        boolean flag1 = equipMapper.update(null, updateWrapper1)>0;
        if (!flag1){
            return new Result(StatusCode.UPDATE_ERR,"更新器材失败");
        }
        //生成报修账单
        Bill bill = new Bill();
        bill.setBillUser(uid);
        bill.setBillPrice(repairPrice);
        bill.setBillType("器材报修");
        bill.setBillTime(LocalDateTime.now());
        bill.setBillDetail("报修"+equip.getEquipName());
        boolean flag2 = billService.insert(bill);
        if (!flag2){
            return new Result(StatusCode.SAVE_ERR,"生成账单失败");
        }
        return new Result(StatusCode.SAVE_OK,true,"报修器材成功");
    }

    @Override
    public Result selectAll(Integer index, Integer size) {
        if (index==0||index==null){
            index=1;
        }if (size==0||size==null){
            size=5;
        }
        Page<Equip> pageInfo = new Page(index,size);
        QueryWrapper<Equip> queryWrapper = new QueryWrapper<>();
        Page<Equip> equipList = (Page)this.equipMapper.selectPage(pageInfo,queryWrapper);
        Integer code = equipList!=null?StatusCode.GET_OK:StatusCode.GET_ERR;
        String msg = equipList!=null?"查询成功":"无相关记录";
        return new Result(code,equipList,msg);
    }

//    @Override
//    public Result selectByTime(String start, String end, String token) {
//        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//        LocalDateTime start1 = LocalDateTime.parse(start,dateTimeFormatter);
//        LocalDateTime end1 = LocalDateTime.parse(end,dateTimeFormatter);
//        QueryWrapper<Equip> queryWrapper = new QueryWrapper<>();
//        queryWrapper.between("equip_createtime",start1,end1);
//        List<Equip> list = equipMapper.selectList(queryWrapper);
//
//        return new Result(1,list,"查询成功");
//    }
}




